# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/3/13 10:21 下午
# @Author : 曹庭
# @File : contents.py
# @Software: PyCharm

from . import api
from course.utils.commons import login_required
from flask import g, current_app, jsonify, request
from course.utils.response_code import RET
from course.utils.image_storage import storage
from course.models import Contents
from course import db, constants
from sqlalchemy.exc import IntegrityError


@api.route("/add_contents", methods=["POST"])
@login_required
def add_contents():
    """
    新增类目
    参数：类目名称，类目级别
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")
    request_dict = request.get_json()
    contents_name = request_dict.get("contents_name")
    contents_level = request_dict.get("contents_level")

    # 校验参数
    if contents_name == "":
        return jsonify(code=RET.PARAMERR, msg="类目名称不能为空")

    contents = Contents(contents_name=contents_name, contents_level=contents_level)
    try:
        db.session.add(contents)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库异常")

    # 返回结果
    return jsonify(code=RET.OK, msg="新增类目成功")


@api.route("/edit_contents", methods=["POST"])
@login_required
def edit_contents():
    """
    修改类目
    参数：类目编号，类目名称，类目级别
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")
    request_dict = request.get_json()
    contents_id = request_dict.get("contents_id")
    contents_name = request_dict.get("contents_name")
    contents_level = request_dict.get("contents_level")

    # 校验参数
    if not all([contents_id, contents_name, contents_level]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    try:
        Contents.query.filter_by(id=contents_id).update({"contents_name": contents_name, "contents_level": contents_level})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="目录修改失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="类目修改成功")


@api.route("/del_contents", methods=["POST"])
@login_required
def del_contents():
    """
    删除类目
    参数：类目编号
    :return:
    """

    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")
    request_dict = request.get_json()
    contents_id = request_dict.get("contents_id")

    # 校验参数
    if not all([contents_id]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    try:
        content = Contents.query.filter_by(contents_level=contents_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DATAEXIST, msg="数据库异常")

    if content:
        return jsonify(code=RET.DBERR, msg="该目录存在子目录，无法删除")
    else:
        try:
            content = Contents.query.filter_by(id=contents_id).first()
            db.session.delete(content)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="目录删除失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="删除成功")


@api.route("/contents_list", methods=["post"])
@login_required
def get_contents_list():
    """
    获取所有类目信息
    :return:
    """


    # 用户信息校验（前端页面需要使用，无需权限验证）
    # user_id = g.user_id
    # if user_id != 1:
    #     return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    req_dict = request.get_json()
    curr = req_dict.get("curr")
    nums = req_dict.get("nums")
    searchParams = req_dict.get("searchParams")
    print(searchParams)

    contents_name = searchParams["contents_name"]

    print(contents_name)

    if contents_name == "":
        try:
            paginate = Contents.query.paginate(page=curr, per_page=nums)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")

        content_list = []

        contents = paginate.items
        total = paginate.total

        for content in contents:
            content_dict = content.to_dict()
            if content_dict["contents_level"] != 0:
                try:
                    content_parent = Contents.query.filter_by(id=content_dict["contents_level"]).first()
                except Exception as e:
                    return jsonify(code=RET.DBERR, msg="数据库查询失败")
                content_dict["contents_level"] = content_parent.contents_name
                content_list.append(content_dict)
            else:
                content_list.append(content_dict)
            print(content_dict)
        print(content_list)

        # 返回结果
        return jsonify(code=RET.OK, count=total, msg="", data=content_list)

    try:
        paginate = Contents.query.filter(Contents.contents_name.like('%{}%'.format(contents_name))).paginate(page=curr, per_page=nums)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    content_list = []
    contents = paginate.items
    total = paginate.total

    for content in contents:
        content_dict = content.to_dict()
        if content_dict["contents_level"] != 0:
            try:
                content_parent = Contents.query.filter_by(id=content_dict["contents_level"]).first()
            except Exception as e:
                return jsonify(code=RET.DBERR, msg="数据库查询失败")
            content_dict["contents_level"] = content_parent.contents_name
            content_list.append(content_dict)
        else:
            content_list.append(content_dict)
        print(content_dict)
        # content_list.append(user_dict)
    print(content_list)

    # 返回结果
    return jsonify(code=RET.OK, count=total, msg="", data=content_list)


@api.route("/contents_parent_list", methods=["post"])
@login_required
def get_contents_parent_list():
    """
    获取所有父类目信息
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")
    try:
        contents = Contents.query.filter_by(contents_level=0).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    content_list = []

    for content in contents:
        content_dict = content.to_dict()
        content_list.append(content_dict)
        print(content_dict)
    print(content_list)

    # 返回结果
    return jsonify(code=RET.OK, msg="", data=content_list)


@api.route("/get_contents_all_list", methods=["post"])
# @login_required
def get_contents_all_list():
    """
    获取所有类目信息
    :return:
    """
    # user_id = g.user_id
    #
    # if user_id != 1:
    #     return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    try:
        contents = Contents.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    content_list = []

    for content in contents:
        content_dict = content.to_dict()
        content_list.append(content_dict)
        print(content_dict)
    print(content_list)

    # 返回结果
    return jsonify(code=RET.OK, msg="", data=content_list)